<template>
  <el-container>
    <el-row>
      <el-col :span="50">
        <el-main>
          <h1>发布图片</h1>
          <!-- 文章分类 -->
          <el-row>
            <el-col>
              <el-select
                v-model="category"
                placeholder="请选择图片分类"
                size="big"
                :filterable="true"
                style="width: 100%"
              >
                <el-option
                  v-for="item in picCategory"
                  :key="item.id"
                  :value="item.category_name"
                  >{{ item.category_name }}</el-option
                >
              </el-select>
            </el-col>
          </el-row>
          <!-- 上传按钮 -->
          <el-row>
            <el-upload
              class="upload-demo"
              action="string"
              accept="image/jpeg, image/png, image/jpg"
              :http-request="uploadSectionFile"
              :on-remove="handleRemove"
              list-type="picture"
              style="width: 100%"
            >
              <el-button size="medium" type="primary">选择图片</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，一次只能成功长传一张
              </div>
            </el-upload>
          </el-row>
          <!-- 上传至服务器 -->
          <el-button
            style="position: absolute; top: 140px; left: 140px"
            size="medium"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          >
        </el-main>
      </el-col>
    </el-row>
  </el-container>
</template>

<script>
// Local Registration
import axios from "axios";
import { mapState } from "vuex";

export default {
  name: "pulishNav",
  data() {
    return {
      category: "", // 图片分类
      OssUrl: "", // 图片上传aliyun返回的url
      files: [], //存放上传的图片数据
    };
  },
  methods: {
    // 图片上传触发的函数   自定义请求:http-request="uploadSectionFile"
    uploadSectionFile(file) {
      const isImage = file.file.type === "image/jpeg";
      if (!isImage) {
        this.$message.error("当前选择的不是图片");
      }
      this.files.push(file.file);
    },
    // 删除图片
    handleRemove(param) {
      var newFiles = this.files.filter((item) => {
        return item.name != param.name;
      });
      this.files = newFiles;
    },

    //上传到服务器(目前只能传类别和图片的路径)
    submitUpload() {
      if (this.category && this.files.length) {
        var formData = new FormData();
        formData.append("category", this.category);
        for (var i = 0; i < this.files.length; i++) {
          formData.append( `file`, this.files[i] );
        }
        this.$axios({
          url: "/api/uploadPic",
          method: "post",
          data: formData,
          async: false,
          contentType: false,
          processData: false,
        }).then(function (res) {
            if (res.data.status == 200) {
              alert("图片上传成功！");
              // location.reload(); //上传成功之后重新刷新页面
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      } else if (this.category) {
        alert("请选择要上传图片");
      } else alert("请选择图片的分类");
    },
  },
  // 钩子 组件加载后运行 查询所有分类
  created: function () {
    // 组件创建之后
    // 在created这个方法中可以操作后端的数据  数据驱动试图
    // 应用：发起Ajax请求
    /* this.$axios
      .get("/api/v1/category/all")
      .then((res) => {
        // 校验后端返回的code
        if (res.data.code === 1000) {
          this.options = res.data.categoryList;
          console.log(res.data.categoryList);
        } else {
          alert("数据获取失败");
        }
      })
      .catch((err) => {
        console.log(err);
      }); */
    this.$store.dispatch("getPicCategory");//为了获取图片分类的
  },
  computed: {
    ...mapState({
      picCategory: (state) => state.category.picCategory,
    }),
  },
};
</script>

<style scoped>
#editor {
  margin: auto;
  width: 100%;
  height: 700px;
}

.el-row {
  margin-bottom: 20px;
}
</style>
